<?php


namespace App\Admin\Services\Auth;


use App\Repositories\Auth\UserRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Admin\Exceptions\Auth\UserException;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserService {
    /**
     * @param array $credentials
     *
     * @return array
     * @throws UserException
     */
    public function doLogin(array $credentials) {
        $password = $credentials["password"];
        if (strpos($credentials["username"], "@") > 0) {//邮箱登陆
            $user = UserRepository::getInstance()->getItemByConditions(["email" => $credentials["username"]], null, true);
        } else {
            $user = UserRepository::getInstance()->getItemByConditions(["name" => $credentials["username"]], null, true);
        }
        
        if (!$user) {
            throw new UserException(1100005);
        }
        
        if (!Hash::check($password, $user['password'])) { //密码不一致
            throw new UserException(1100006);
        }
        
        $token = JWTAuth::fromUser($user);
        
        return [
            'status'     => 'ok',
            'token'      => $token,
            'expires_in' => Auth::guard()->factory()->getTTL() * 60
        ];
    }
}